<template>
  <div class="article-page bg-gray-50">
    <!-- 加载状态 -->
    <div
      v-if="articleDetailStore.loading"
      class="loading-container"
    >
      <LoadingSpinner />
      <p class="mt-4 text-gray-600">
        正在加载条文详情...
      </p>
    </div>

    <!-- 错误状态 -->
    <div
      v-else-if="articleDetailStore.error"
      class="error-container"
    >
      <div class="error-content">
        <ExclamationTriangleIcon class="w-16 h-16 text-red-500 mx-auto mb-4" />
        <h2 class="text-xl font-semibold text-gray-900 mb-2">
          加载失败
        </h2>
        <p class="text-gray-600 mb-6">
          {{ articleDetailStore.error }}
        </p>
        <div class="space-x-4">
          <button
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
            @click="loadArticleData"
          >
            重新加载
          </button>
          <button
            class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300"
            @click="goBack"
          >
            返回
          </button>
        </div>
      </div>
    </div>

    <!-- 主要内容 -->
    <div
      v-else-if="articleDetailStore.currentArticle"
      class="article-content"
    >
      <!-- 头部导航 -->
      <div class="article-header bg-white border-b border-gray-200 sticky top-0 z-10">
        <div class="container mx-auto px-4 py-4">
          <!-- 面包屑导航 -->
          <nav class="breadcrumb mb-4">
            <ol class="flex items-center space-x-2 text-sm text-gray-600">
              <li>
                <router-link
                  to="/"
                  class="hover:text-blue-600"
                >
                  首页
                </router-link>
              </li>
              <ChevronRightIcon class="w-4 h-4" />
              <li>
                <router-link
                  to="/browse"
                  class="hover:text-blue-600"
                >
                  浏览
                </router-link>
              </li>
              <ChevronRightIcon class="w-4 h-4" />
              <li v-if="articleDetailStore.chapterInfo">
                <router-link 
                  :to="`/browse/${articleDetailStore.chapterInfo.part}-${articleDetailStore.chapterInfo.chapter}`"
                  class="hover:text-blue-600"
                >
                  {{ articleDetailStore.chapterInfo.part }}
                </router-link>
              </li>
              <ChevronRightIcon class="w-4 h-4" />
              <li class="text-gray-900 font-medium">
                {{ articleDetailStore.currentArticle.article_number }}
              </li>
            </ol>
          </nav>

          <!-- 操作按钮 -->
          <div class="flex items-center justify-between">
            <button
              class="flex items-center space-x-2 text-gray-600 hover:text-gray-900"
              @click="goBack"
            >
              <ArrowLeftIcon class="w-5 h-5" />
              <span>返回</span>
            </button>
            
            <div class="flex items-center space-x-3">
              <!-- 收藏按钮 -->
              <button
                :class="[
                  'flex items-center space-x-2 px-4 py-2 rounded-lg transition-colors',
                  articleDetailStore.isFavorited
                    ? 'bg-red-50 text-red-600 hover:bg-red-100'
                    : 'bg-gray-50 text-gray-600 hover:bg-gray-100'
                ]"
                @click="articleDetailStore.toggleFavorite"
              >
                <HeartIcon 
                  :class="[
                    'w-5 h-5',
                    articleDetailStore.isFavorited ? 'fill-current' : ''
                  ]"
                />
                <span>{{ articleDetailStore.isFavorited ? '已收藏' : '收藏' }}</span>
              </button>

              <!-- 分享按钮 -->
              <button
                class="flex items-center space-x-2 px-4 py-2 bg-gray-50 text-gray-600 rounded-lg hover:bg-gray-100"
                @click="articleDetailStore.shareArticle"
              >
                <ShareIcon class="w-5 h-5" />
                <span>分享</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 文章主体 -->
      <div class="article-body bg-white">
        <div class="container mx-auto px-4 py-8">
          <div class="max-w-4xl mx-auto">
            <!-- 条文标题 -->
            <div class="article-title-section mb-8">
              <h1 class="article-number text-3xl font-bold text-blue-600 mb-4">
                {{ articleDetailStore.currentArticle.article_number }}
              </h1>
              <h2 class="article-title text-xl text-gray-700 leading-relaxed">
                {{ articleDetailStore.articleTitle }}
              </h2>
            </div>

            <!-- 条文内容 -->
            <div class="article-content-section mb-8">
              <div class="content-box bg-gray-50 rounded-lg p-6 shadow-sm">
                <p class="article-text text-lg leading-relaxed text-gray-900">
                  {{ articleDetailStore.articleContent }}
                </p>
              </div>
            </div>

            <!-- 元数据信息 -->
            <div class="article-meta mb-8">
              <div class="meta-grid bg-white rounded-lg border border-gray-200 p-6">
                <div class="meta-item">
                  <h3 class="meta-label text-sm font-medium text-gray-500 mb-1">
                    所属编章
                  </h3>
                  <p class="meta-value text-gray-900">
                    {{ articleDetailStore.chapterInfo?.part }} 
                    第{{ articleDetailStore.chapterInfo?.chapter }}章
                  </p>
                </div>
                <div class="meta-item">
                  <h3 class="meta-label text-sm font-medium text-gray-500 mb-1">
                    生效日期
                  </h3>
                  <p class="meta-value text-gray-900">
                    {{ articleDetailStore.currentArticle.effective_date }}
                  </p>
                </div>
                <div
                  v-if="articleDetailStore.navigationInfo.totalInChapter > 0"
                  class="meta-item"
                >
                  <h3 class="meta-label text-sm font-medium text-gray-500 mb-1">
                    章节位置
                  </h3>
                  <p class="meta-value text-gray-900">
                    第 {{ articleDetailStore.navigationInfo.currentIndex }} 条 / 
                    共 {{ articleDetailStore.navigationInfo.totalInChapter }} 条
                  </p>
                </div>
                <div
                  v-if="articleDetailStore.keywords.length > 0"
                  class="meta-item"
                >
                  <h3 class="meta-label text-sm font-medium text-gray-500 mb-1">
                    关键词
                  </h3>
                  <div class="keywords flex flex-wrap gap-2">
                    <span
                      v-for="keyword in articleDetailStore.keywords.slice(0, 8)"
                      :key="keyword"
                      class="keyword-tag px-2 py-1 bg-blue-100 text-blue-700 text-sm rounded"
                    >
                      {{ keyword }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 条文导航 -->
      <div
        v-if="hasNavigation"
        class="article-navigation"
      >
        <div class="container mx-auto px-4 py-6">
          <div class="max-w-4xl mx-auto">
            <div class="nav-container bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
              <div class="nav-header bg-gray-50 px-6 py-3 border-b border-gray-100">
                <h3 class="text-base font-medium text-gray-700">
                  条文导航
                </h3>
              </div>
              
              <div class="nav-buttons p-4 sm:p-6">
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <!-- 上一条 -->
                  <router-link
                    v-if="articleDetailStore.navigationInfo.prevArticle"
                    :to="articleDetailStore.navigateToArticle(articleDetailStore.navigationInfo.prevArticle.article_number)"
                    class="nav-button prev-button group block p-5 sm:p-4 rounded-xl border border-gray-200 hover:border-blue-300 hover:bg-blue-50 active:bg-blue-100 transition-all duration-200"
                  >
                    <div class="flex items-center space-x-4 sm:space-x-3">
                      <div class="flex-shrink-0">
                        <ArrowLeftIcon class="w-6 h-6 sm:w-5 sm:h-5 text-gray-400 group-hover:text-blue-500 transition-colors" />
                      </div>
                      <div class="flex-1 min-w-0">
                        <div class="nav-direction text-sm sm:text-xs text-gray-500 mb-1.5 sm:mb-1">
                          上一条
                        </div>
                        <div class="nav-number text-base sm:text-sm font-bold sm:font-semibold text-gray-900 group-hover:text-blue-600 transition-colors mb-1">
                          {{ articleDetailStore.navigationInfo.prevArticle.article_number }}
                        </div>
                        <div
                          class="nav-content text-sm sm:text-xs text-gray-600 line-clamp-2 sm:truncate leading-relaxed"
                          :title="articleDetailStore.navigationInfo.prevArticle.title"
                        >
                          {{ articleDetailStore.navigationInfo.prevArticle.title }}
                        </div>
                      </div>
                    </div>
                  </router-link>

                  <!-- 下一条 -->
                  <router-link
                    v-if="articleDetailStore.navigationInfo.nextArticle"
                    :to="articleDetailStore.navigateToArticle(articleDetailStore.navigationInfo.nextArticle.article_number)"
                    class="nav-button next-button group block p-5 sm:p-4 rounded-xl border border-gray-200 hover:border-blue-300 hover:bg-blue-50 active:bg-blue-100 transition-all duration-200"
                  >
                    <div class="flex items-center space-x-4 sm:space-x-3">
                      <div class="flex-shrink-0 sm:order-2">
                        <ArrowRightIcon class="w-6 h-6 sm:w-5 sm:h-5 text-gray-400 group-hover:text-blue-500 transition-colors" />
                      </div>
                      <div class="flex-1 min-w-0 text-left sm:text-right sm:order-1">
                        <div class="nav-direction text-sm sm:text-xs text-gray-500 mb-1.5 sm:mb-1">
                          下一条
                        </div>
                        <div class="nav-number text-base sm:text-sm font-bold sm:font-semibold text-gray-900 group-hover:text-blue-600 transition-colors mb-1">
                          {{ articleDetailStore.navigationInfo.nextArticle.article_number }}
                        </div>
                        <div
                          class="nav-content text-sm sm:text-xs text-gray-600 line-clamp-2 sm:truncate leading-relaxed"
                          :title="articleDetailStore.navigationInfo.nextArticle.title"
                        >
                          {{ articleDetailStore.navigationInfo.nextArticle.title }}
                        </div>
                      </div>
                    </div>
                  </router-link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 相关推荐 -->
      <div
        v-if="articleDetailStore.relatedArticles.length > 0"
        class="related-articles"
      >
        <div class="container mx-auto px-4 py-8">
          <div class="max-w-4xl mx-auto">
            <h3 class="section-title text-xl font-semibold text-gray-900 mb-6">
              相关条文
            </h3>
            <div class="related-grid grid grid-cols-1 md:grid-cols-2 gap-4">
              <router-link
                v-for="article in articleDetailStore.relatedArticles"
                :key="article._id"
                :to="articleDetailStore.navigateToArticle(article.article_number)"
                class="related-item p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
              >
                <div class="related-number text-sm font-medium text-blue-600 mb-1">
                  {{ article.article_number }}
                </div>
                <div class="related-title text-gray-900 text-sm leading-relaxed line-clamp-2">
                  {{ article.title }}
                </div>
              </router-link>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div
      v-else
      class="empty-state"
    >
      <div class="empty-content">
        <DocumentIcon class="w-16 h-16 text-gray-400 mx-auto mb-4" />
        <h2 class="text-xl font-semibold text-gray-900 mb-2">
          条文不存在
        </h2>
        <p class="text-gray-600 mb-6">
          请检查条文编号是否正确
        </p>
        <router-link
          to="/browse"
          class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          返回浏览
        </router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useArticleDetailStore } from '@/stores/articleDetail'
import { 
  ArrowLeftIcon, 
  ArrowRightIcon, 
  ChevronRightIcon,
  HeartIcon, 
  ShareIcon,
  ExclamationTriangleIcon,
  DocumentIcon
} from '@heroicons/vue/24/outline'
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'

// 路由和store
const route = useRoute()
const router = useRouter()
const articleDetailStore = useArticleDetailStore()

// 计算属性
const hasNavigation = computed(() => {
  return articleDetailStore.navigationInfo.prevArticle || 
         articleDetailStore.navigationInfo.nextArticle
})

// 方法
const loadArticleData = async () => {
  const articleId = route.params.id
  console.log('[Article.vue] 准备加载条文，ID:', articleId)
  if (articleId) {
    try {
      console.log('[Article.vue] 调用store加载条文...')
      await articleDetailStore.loadArticle(articleId)
      console.log('[Article.vue] 条文加载完成')
    } catch (err) {
      console.error('[Article.vue] 条文加载失败:', err)
    }
  }
  else {
    console.warn('[Article.vue] 未提供条文ID')
  }
}

const goBack = () => {
  if (window.history.length > 1) {
    router.back()
  }
  else {
    router.push('/browse')
  }
}

// 监听路由变化
watch(() => route.params.id, async (newId, oldId) => {
  if (newId && newId !== oldId) {
    await loadArticleData()
  }
})

// 生命周期
onMounted(async () => {
  await loadArticleData()
})

onUnmounted(() => {
  articleDetailStore.reset()
})
</script>

<style scoped>
.article-page {
  @apply min-h-screen;
}

.loading-container,
.error-container,
.empty-state {
  @apply flex flex-col items-center justify-center min-h-screen text-center p-8;
}

.error-content,
.empty-content {
  @apply max-w-md;
}

.article-header {
  @apply sticky top-0 z-10;
}

.article-body {
  @apply bg-white;
}

.article-number {
  @apply text-blue-600;
}

.article-title {
  @apply leading-relaxed;
}

.article-text {
  @apply leading-8;
}

.content-box {
  @apply rounded-lg p-6;
}

.meta-grid {
  @apply p-6;
}

.keyword-tag {
  @apply cursor-pointer transition-colors;
}

.nav-container {
  @apply rounded-xl overflow-hidden;
}

.nav-header {
  @apply px-6 py-3 border-b;
}

.nav-button {
  @apply block no-underline;
}

.nav-button:hover .nav-title {
  @apply text-blue-600;
}

.related-item {
  @apply p-4 rounded-lg transition-colors;
}

.related-number {
  @apply text-blue-600;
}

.related-item:hover .related-number {
  @apply text-blue-700;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 移动端优化 */
@media (max-width: 640px) {
  .article-number {
    @apply text-2xl;
  }
  
  .article-title {
    @apply text-lg;
  }
  
  .article-text {
    @apply text-base leading-7;
  }
  
  .nav-buttons {
    @apply space-y-4;
  }
  
  .related-grid {
    @apply grid-cols-1;
  }
}

/* 无障碍优化 */
@media (prefers-reduced-motion: reduce) {
  * {
    @apply transition-none;
  }
}

/* 打印样式 */
@media print {
  .article-header,
  .article-navigation,
  .related-articles {
    @apply hidden;
  }
  
  .article-body {
    @apply bg-white shadow-none;
  }
}
</style>
